package com.surveypark.struts2.action;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.surveypark.domain.User;
import com.surveypark.service.UserService;
import com.surveypark.util.DataUtil;
import com.surveypark.util.ValidateUtil;

@Controller("regAction")
@Scope("prototype")
public class RegAction extends BaseAction<User> {

	private static final long serialVersionUID = -4155649679878006751L;

	private String confirmPassword;

	@Resource(name = "userService")
	private UserService userService;

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

//	@Override
//	public User getModel() {
//		// TODO Auto-generated method stub
//		return model;
//	}

	/**
	 * ����ע��ҳ��
	 * 
	 * @return
	 */
	@SkipValidation
	public String toRegPage() {

		return "regPage";
	}

	/**
	 * ����ע��
	 * 
	 * @return
	 */
	public String doReg() {

		User user = new User();
		BeanUtils.copyProperties(model, user);
		user.setPassword(DataUtil.MD5Encrypt(user.getPassword()));
		userService.saveEntity(user);
		ActionContext.getContext().put("user", user);
		return "success";
	}

	@Override
	public void validate() {
		if (!ValidateUtil.isValid(model.getEmail())) {

			addFieldError("email", "请输入邮箱");
		}
		if (!ValidateUtil.isValid(model.getNickName())) {

			addFieldError("nickName", "请输入昵称");
		}
		if (!ValidateUtil.isValid(model.getPassword())) {

			addFieldError("password", "请输入密码");
		}

		if (hasFieldErrors()) {
			return;
		}

		// ��֤�ظ�����
		if (!model.getPassword().equals(confirmPassword)) {

			addFieldError("password", "两次输入密码不一致");
			return;
		}
		User user = userService.getEntity(1);
		System.out.println(user);
		// ��֤������Ч��
		boolean isExists = userService.isRegister(model.getEmail());

		if (isExists) {

			addFieldError("email", "邮箱已被占用");
		}
	}
}
